package com.apps.ftapp.activity;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.apps.ftapp.R;
import com.apps.ftapp.adapter.DbPlayBackAdapter;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.DateUtil;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.ScreenUtils;
import com.apps.ftapp.util.StatusBarUtils;
import com.apps.ftapp.util.ZipUtil;
import com.duobeiyun.bean.ChatBean;
import com.duobeiyun.callback.OfflinePlaybackMessageCallback;
import com.duobeiyun.callback.VideoCallback;
import com.duobeiyun.util.CommonUtils;
import com.duobeiyun.util.DuobeiYunClient;
import com.duobeiyun.widget.OfflinePlaybackPlayer;
import com.duobeiyun.widget.OfflinePlayerView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import me.leefeng.promptlibrary.PromptDialog;

public class DbPlayBack2Activity extends BaseActivity implements OfflinePlaybackMessageCallback, VideoCallback {

    @BindView(R.id.player)
    OfflinePlayerView playerView;
    @BindView(R.id.mSeekBar)
    SeekBar mSeekBar;
    @BindView(R.id.listView)
    ListView listView;
    @BindView(R.id.beisu)
    TextView beisu;
    @BindView(R.id.mseekrel)
    RelativeLayout mseekrel;
    @BindView(R.id.zanting)
    TextView zanting;
    @BindView(R.id.shijian)
    TextView shijian;
    @BindView(R.id.beisu2)
    TextView beisu2;
    @BindView(R.id.back_lin)
    LinearLayout back_lin;


    private PromptDialog promptDialog;

    private float speed = 1f;

    private DbPlayBackAdapter dbPlayBackAdapter;
    private OfflinePlaybackPlayer player;

    private String roomId;
    private String filePath;


    private List<ChatBean> datalist = new ArrayList<>();


    private Handler handler = null;

    public DbPlayBack2Activity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_db_play_back);
        ButterKnife.bind(this);

//        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
//                ViewGroup.LayoutParams.WRAP_CONTENT);
//        int width = layoutParams.width = CommonUtils.getScreenWidth(this);
//        layoutParams.height = width * 3 / 4;
////        layoutParams.width=width;
//        L.i("main", "==========" + width);
//        player.setLayoutParams(layoutParams);


        if (getOrientation(this)) {
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            int width = layoutParams.width = CommonUtils.getScreenWidth(this);
            layoutParams.height = width * 3 / 4;
            playerView.setLayoutParams(layoutParams);
        }

        player = new OfflinePlaybackPlayer(this.getApplicationContext(), playerView);



        quanping.setVisibility(View.VISIBLE);
        //创建属于主线程的handler
        handler = new Handler();
        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        roomId = bundle.getString("roomId");
        filePath = bundle.getString("filePath");
        final String title = bundle.getString("title");

        L.i("main", "filePath::::" + filePath + roomId + "::::" + roomId);
        StatusBarUtils.StatusBarLightMode(this);

        setTitle(title);

        quanping.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                L.i("main", "切换成横屏");
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                quanping.setVisibility(View.GONE);
                listView.setVisibility(View.GONE);
                toolbar.setVisibility(View.GONE);
                back_lin.setVisibility(View.VISIBLE);
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                playerView.setLayoutParams(layoutParams);


//                toolbar.setVisibility(View.GONE);/
//                settings.setUseWideViewPort(true);
//                settings.setLoadWithOverviewMode(true);

//                LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) player.getLayoutParams();
//                linearParams.height = ScreenUtils.getScreenHeight(getApplicationContext());// 控件的高强制设成20
                //


            }
        });

        beisu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changespeed();

            }
        });


        beisu2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changespeed();
            }
        });

        back_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //横屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//                    LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) mWebView.getLayoutParams();
//                    linearParams.height = ScreenUtils.getScreenHeight(getApplicationContext());// 控件的高强制设成20
//                    mWebView.setLayoutParams(linearParams);


                quanping.setVisibility(View.VISIBLE);
                listView.setVisibility(View.VISIBLE);
                toolbar.setVisibility(View.VISIBLE);


                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                int width = layoutParams.width = ScreenUtils.getScreenWidth(getApplicationContext());
                layoutParams.height = width * 3 / 4;

                L.i("main", "==========" + width);
//                    layoutParams.width=width;
                playerView.setLayoutParams(layoutParams);
//                    player.play();


                back_lin.setVisibility(View.GONE);
            }
        });

        zanting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView t = (TextView) v;
                String text = t.getText().toString();
                if ("暂停".equals(text)) {

                    player.pause();
                    t.setText("播放");
                } else {
                    player.play();

                    t.setText("暂停");
                }
            }
        });
        //判断
        File file = new File(filePath + roomId);
        if (!file.exists()) {
            promptDialog = new PromptDialog(DbPlayBack2Activity.this);
            promptDialog.showLoading("视频解压中,请勿关闭....");
//
//            ZipUtil.upzipFile(filePath+"/"+roomId+".zip", filePath);
//            promptDialog.dismiss();


//            player.play();//开始播放
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ZipUtil.upzipFile(filePath + "/" + roomId + ".zip", filePath);
                    handler.post(runnableUi);

                }
            }).start();


//            //先解压
//            promptDialog = new PromptDialog(this);
//            promptDialog.showLoading("视频缓冲中..");
//            ZipUtil.upzipFile(filePath+"/"+roomId+".zip", filePath);
//            promptDialog.dismiss();
        } else {
//            DuobeiYunClient.setSavePath(filePath);
//            player.init(Constant.DES_KEY);//des_key请向商务获取
//            player.setCallback(roomId, this);//roomId;即下载资源的课程的roomId;
//            player.setSeekBar(mSeekBar);
            DuobeiYunClient.setSavePath(filePath);
            player.init(Constant.DES_KEY);//des_key请向商务获取
            player.setCallback(roomId, this);//roomId;即下载资源的课程的roomId;
            player.setSeekBar(mSeekBar);
//            player.set
//            player.setKeepScreenOn(true);


            player.play();//开始播放

            initView();


        }


    }


    /**
     * 点击改变播放速度
     */
    public void changespeed() {
        if (speed == 1f) {
            speed = 1.2f;
            beisu.setText("1.2");
        } else if (speed == 1.2f) {
            speed = 1.5f;
            beisu.setText("1.5");
        } else if (speed == 1.5f) {
            speed = 1.8f;
            beisu.setText("1.8");
        } else if (speed == 1.8f) {
            speed = 2.0f;
            beisu.setText("2.0");
        } else if (speed == 2.0f) {
            speed = 1f;
            beisu.setText("1");
        }

        player.setPlaybackSpeed(speed);
    }

    /**
     *
     */
    private void initView() {

        dbPlayBackAdapter = new DbPlayBackAdapter(getApplicationContext(), datalist);
        listView.setAdapter(dbPlayBackAdapter);

    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:

                if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    //竖屏
//                    mWebView.goBack();
                    finish();
                } else {
                    //横屏
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//                    LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) mWebView.getLayoutParams();
//                    linearParams.height = ScreenUtils.getScreenHeight(getApplicationContext());// 控件的高强制设成20
//                    mWebView.setLayoutParams(linearParams);


                    quanping.setVisibility(View.VISIBLE);
                    listView.setVisibility(View.VISIBLE);
                    toolbar.setVisibility(View.VISIBLE);


                    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT);
                    int width = layoutParams.width = ScreenUtils.getScreenWidth(getApplicationContext());
                    layoutParams.height = width * 3 / 4;

                    L.i("main", "==========" + width);
//                    layoutParams.width=width;
                    playerView.setLayoutParams(layoutParams);
//                    player.play();
                    back_lin.setVisibility(View.GONE);


                }


//                /** 回退键 事件处理 优先级:视频播放全屏-网页回退-关闭页面 */
//                if (customView != null) {
////                    hideCustomView();
//                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//                } else if (mWebView.canGoBack()) {
//                    mWebView.goBack();
//                } else {
//                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//                }
                return true;
            default:
                return super.onKeyUp(keyCode, event);
        }
    }


    // 构建Runnable对象，在runnable中更新界面
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            //更新界面
            play();
        }

    };


    private void play() {
        L.i("main", "--------------------------------");
        promptDialog.dismiss();
        DuobeiYunClient.setSavePath(filePath);
        player.init(Constant.DES_KEY);//des_key请向商务获取
        player.setCallback(roomId, this);//roomId;即下载资源的课程的roomId;
        player.setSeekBar(mSeekBar);

        player.play();//开始播放
    }


    private boolean unzp() {
        //先解压

        ZipUtil.upzipFile(filePath + "/" + roomId + ".zip", filePath);
        promptDialog.dismiss();


        DuobeiYunClient.setSavePath(filePath);
        player.init(Constant.DES_KEY);//des_key请向商务获取
        player.setCallback(roomId, this);//roomId;即下载资源的课程的roomId;
        player.setSeekBar(mSeekBar);
        player.play();//开始播放

        return true;
    }


    @Override
    public void handleContentList(final List<ChatBean> list) {
        if (null != list && list.size() > 0) {
            for (ChatBean chatBean : list) {

            }

        }
        L.i("main", ":handleContentList::::");


        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                dbPlayBackAdapter.addRes(list);
            }
        });


//        dbPlayBackAdapter.notifyDataSetChanged();
    }

    @Override
    public void handleContent(final ChatBean chatBean) {


//

        L.i("main", ":::chatBean::" + chatBean.getMessage() + "::::" + DateUtil.timeStamp2Date(chatBean.getTimestamp() + "", "hh:mm") + "::::" + chatBean.getUsername());


        L.i("main", "======ebd=======");

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                dbPlayBackAdapter.addRes(chatBean);
            }
        });

//        if(null!=datalist&&datalist.size()>0){
//
//            for(ChatBean c:datalist){
//                if(Tools.isNull(c.getUid()).equals(chatBean.getUid())&&Tools.isNull(c.getMessage()).equals(chatBean.getMessage())&&Tools.isNull(c.getTimestamp()).equals(chatBean.getTimestamp())){
//                    L.i("main",".........此人评论过......");
//                }else{
//                    L.i("main",".........评论......");
//
//                    runOnUiThread(new Runnable() {
//
//                        @Override
//                        public void run() {
//                            // TODO Auto-generated method stub
//                            dbPlayBackAdapter.addRes(chatBean);
//                        }
//                    });
//                }
//            }
//
//        }else{
//
//            runOnUiThread(new Runnable() {
//
//                @Override
//                public void run() {
//                    // TODO Auto-generated method stub
//                    dbPlayBackAdapter.addRes(chatBean);
//                }
//            });
//
//
//        }


    }

    @Override
    public void handleErrorMessage(Exception e) {
        L.i("main", ":::handleErrorMessage::" + e);
    }

    @Override
    public void loadStart() {
        L.i("main", ":::loadStart::");
    }

    @Override
    public void loadFinish() {
        L.i("main", ":::loadFinish::");
    }

    @Override
    public void playFinish() {
        L.i("main", ":::playFinish::");
    }

    @Override
    public void statusCode(int i) {

        L.i("main", ":::statusCode::" + i);
    }

    @Override
    public void exit() {
        L.i("main", ":::exit::");
    }

    @Override
    public void currentTime(final String s, int i) {
        L.i("main", ":::currentTime::" + s + "...." + i);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                shijian.setText(s);
            }
        });

    }

    @Override
    public void initPPT(String s, String s1, String s2) {
        L.i("main", ":::initPPT=========::");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        player.destroy();
    }

    public static boolean getOrientation(Context context) {
        return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }


    @Override
    public void showvideo(int i) {

    }

    @Override
    public void hidenVideo(int i) {

    }
}
